package src.com.neusoft.nep.common;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdFileUtils {
    public static Map readMapObject(String fileName) {
        File file = new File(fileName);
        Map map = null;
        try {
            if (file.length() == 0) {
                map = new HashMap<>();
            } else {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);
                map = (Map) ois.readObject();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    public static void writeObject(String fileName, Map map) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {//若文件不存在
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Map<String, String>> readListMapObject(String fileName) {
        File file = new File(fileName);
        List<Map<String, String>> list = null;

        try {
            if (file.length() == 0) {
                list = new ArrayList<>(); // 文件为空时返回空列表
            } else {
                try (FileInputStream fis = new FileInputStream(file);
                     ObjectInputStream ois = new ObjectInputStream(fis)) {

                    list = (List<Map<String, String>>) ois.readObject();
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在时返回空列表而非抛出异常
            list = new ArrayList<>();
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException("读取文件失败: " + e.getMessage(), e);
        }

        return list != null ? list : new ArrayList<>();
    }

    // 将List<Map<String, String>>对象写入文件
    public static void writeListMapObject(String fileName, List<Map<String, String>> list) {
        try (FileOutputStream fos = new FileOutputStream(fileName);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            oos.writeObject(list);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException("写入文件失败: " + e.getMessage(), e);
        }
    }
}

